package com.spbl.common.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.LinkedHashMap;


/**
 * Description(统一返回格式)
 * author: Gao xueyong
 * Create at: 2020/4/19 7:47 下午
 */
@Slf4j
@Configuration
@RestControllerAdvice
public class GlobalReturnConfig implements ResponseBodyAdvice<Object> {
    private static final String error = "error";
    private static final String message = "message";
    private static final String path = "path";
    private static final String status = "status";

    /**
     * 判断那些需要拦截
     *
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof Result) {
            return o;
        }
        if (o instanceof LinkedHashMap) {
            JSONObject js = (JSONObject) JSON.toJSON(o);
            Integer tempStatus = js.getInteger(status);
            String tempError = js.getString(error);
            String tempMessage = js.getString(message);
            if (null != tempStatus && StringUtils.isNotBlank(tempError) && StringUtils.isNotBlank(tempMessage)) {
                log.error("请求错误：{}", o);
                return Result.renderError(tempStatus, tempMessage, null);
            }
        }
        return Result.renderSuccess(ErrorTypeEnum.SERVICE_SUCCESS.getCode(), ErrorTypeEnum.SERVICE_SUCCESS.getMessage(), o);
    }
}
